<?php
/**
 * Author:xsc
 * Time:2023/9/5 16:03
 */

namespace App\Extensions\Common;

use App\Extensions\BaseService;
use App\Common\ResponseCode;
use App\Exceptions\BusinessException;
use OSS\OssClient;
use Illuminate\Support\Facades\Log;

class OssService extends BaseService
{

    private $access_key_id;

    private $access_key_secret;

    private $endpoint;

    public $bucket;

    public function __construct()
    {
        $this->access_key_id = config('oss.access_key_id');
        $this->access_key_secret = config('oss.access_key_secret');
        $this->endpoint = config('oss.endpoint');
        $this->bucket = config('oss.bucket');
    }

    /**
     * 转存文件
     * @param $url
     * @return array|string|string[]
     * @throws BusinessException
     * @throws \OSS\Core\OssException
     * Author:xsc
     * Time:2023/9/5 16:51
     */
    public function saveFile($url)
    {
        $pathinfoCheck = pathinfo($url);
        if (!isset($pathinfoCheck['extension']))
            throw new BusinessException(ResponseCode::FILE_EXTENSION_ERROR);
        $extension = $pathinfoCheck['extension'] ?: '';

        $allow_extension = ['jpg', 'jpeg', 'gif', 'bmp', 'png'];

        // 指定图片后缀
        if (!in_array($extension, $allow_extension)) {
            throw new BusinessException(ResponseCode::FILE_EXTENSION_ERROR);
        }

        // 远程文件转存本地
        $temp_url = $this->downloadRemoteFile($url);

        // 上传oss的文件名
        $filename = 'uplaods/image/' . date("Ymd") . '/' . sha1(date('YmdHis', time()) . uniqid()) . '.' . $extension;

        // 实例化oss
        $client = new OssClient($this->access_key_id, $this->access_key_secret, $this->endpoint, false);

        // 上传oss
        $res = $client->uploadFile($this->bucket, $filename, $temp_url);

        if (!$res) {
            throw new BusinessException(ResponseCode::FILE_SAVE_ERROR);
        }

        // 删除本地文件
        @unlink($temp_url);

        $path = str_ireplace(env('OSS_SEARCH'), env('OSS_OUT_URL'), $res['info']['url']);

        return $path;
    }

    /**
     * 远程文件临时转存本地
     * @param $url
     * @return string
     * Author:xsc
     * Time:2023/9/5 17:33
     */
    private function downloadRemoteFile($url)
    {
        $dir = base_path() . '/public/uploads';
        if (!file_exists($dir)) {
            mkdir($dir, 0777);
        }
        $temp_url = $dir . '/' . sha1(date('YmdHis', time()) . uniqid()) . '.' . pathinfo($url)['extension'];

        file_put_contents($temp_url, file_get_contents($url));

        return $temp_url;
    }


}
